package com.jams.goodox.activity.mine.personal;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.facebook.drawee.view.SimpleDraweeView;
import com.hangzhou.jin.customview.TextMoreLayout;
import com.jams.goodox.BaseActivity;
import com.jams.goodox.R;
import com.jams.goodox.SePref;
import com.jams.goodox.activity.home.MineInfo;
import com.jams.goodox.activity.login.AddressPickTask;
import com.jams.goodox.activity.qa.GlideCircleTransform;
import com.jams.goodox.listen.SuccessListener;
import com.jams.goodox.net.services.LoginService;
import com.jams.goodox.utils.PhotoSelectUtils;
import com.jams.goodox.utils.StatusBarCompat;
import com.jams.goodox.utils.StyleUtil;
import com.jams.goodox.utils.TipAlertDialog;
import com.jams.goodox.utils.ToastUtil;
import com.jams.goodox.utils.Utils;
import com.jams.goodox.widget.ActionSheetDialog;

import org.json.JSONObject;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.OnClick;
import cn.addapp.pickers.entity.City;
import cn.addapp.pickers.entity.County;
import cn.addapp.pickers.entity.Province;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

//我的资料
public class MyInfoActivity extends BaseActivity {

    private static final String TAG = "MyInfoActivity";
    @Bind(R.id.headimg)
    SimpleDraweeView headimg;
    @Bind(R.id.rl1)
    RelativeLayout rl1;
    @Bind(R.id.nickname)
    TextMoreLayout nickname;
    @Bind(R.id.sex)
    TextMoreLayout sex;
    @Bind(R.id.birthDay)
    TextMoreLayout birthDay;
    @Bind(R.id.connect_company)
    TextMoreLayout connectCompany;
    @Bind(R.id.phonenum)
    TextMoreLayout phonenum;
    @Bind(R.id.password)
    TextMoreLayout password;
    @Bind(R.id.password_pay)
    TextMoreLayout passwordPay;
    @Bind(R.id.quit_account)
    TextView quitAccount;
    @Bind(R.id.mask)
    RelativeLayout mask;

    private final static int nickname_request = 99;//修改昵称
    private final static int change_portrait = 10;//修改头像
    private final static int change_phone = 11;//修改手机号码
    private final static int connect_company = 12;//关联企业
    private MineInfo user;

    private boolean isTeacher;
    String gradeTx;

    private PhotoSelectUtils mPhotoSelectUtils;
    String headImagePath;


    @Override
    protected int getLayoutId() {
        return R.layout.activity_my_info;
    }

    @Override
    protected void init() {
        StyleUtil.titleBackKey(this, "编辑资料");
        StatusBarCompat.compat(this, ContextCompat.getColor(this, R.color.main_theme));//沉侵式头部
        isTeacher = SePref.getMemberType() == 1 ? false:true;
        //user = ( MineFragment.MineInfo) getIntent().getSerializableExtra("mineInfo");
        //if (user != null) {
        //setData();
        setData();
        //}
        isTeacher = SePref.getMemberType() == 1 ? false:true;
    }

    private void setData() {
        //FrescoUtil.loadNetUrl(headimg, StringUtils.newString(user.getImgPath()));
        Glide.with(MyInfoActivity.this).load(SePref.getHeadImageUrl())
                .placeholder(R.drawable.loading) //占位符 也就是加载中的图片，可放个gif
                .error(R.mipmap.morentouxiang60) //失败图片
                .bitmapTransform(new GlideCircleTransform(MyInfoActivity.this)).crossFade(1000).into(headimg);

        nickname.setRightText(SePref.getNickName());
        passwordPay.setRightText(SePref.getGrade());
        if(isTeacher){
            passwordPay.setLeftText("头衔介绍");
            passwordPay.setRightText(SePref.getIndividualitySign());
        }else {
            passwordPay.setLeftText("孩子年级");
            passwordPay.setRightText(SePref.getGrade());
        }
        nickname.setRightText(SePref.getNickName());
        if(!TextUtils.isEmpty(SePref.getHeadImageUrl())){
            headimg.setImageURI(SePref.getHeadImageUrl());
        }
    }

    @OnClick({R.id.rl1, R.id.nickname, R.id.sex, R.id.birthDay, R.id.connect_company, R.id.phonenum, R.id.password, R.id.password_pay, R.id.quit_account})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.rl1:
                //startActivityForResult(new Intent(this, SelectUpPopupWindow.class), change_portrait);
                showPop();

                break;
            case R.id.nickname:
                Bundle b = new Bundle();
//                b.putString("nickname", user != null ? user.getNickName() : "");
//                b.putBoolean("isTouxian", false);
                qStartActivityForResult(EditPersonalInfoActivity.class, b, nickname_request);
                break;
            case R.id.sex:
                break;
            case R.id.birthDay:
                break;
//            case R.id.connect_company:
//                Intent intent = new Intent(this, ConnectPersonalCompanyActivity.class);
//                intent.putExtra("user", user);
//                startActivityForResult(intent, connect_company);
//                break;
            case R.id.phonenum:
                Bundle num = new Bundle();
                num.putInt(MinePersonalSettingsEditPhoneNumActivity.FromType, 301);
                num.putBoolean("isTeacher", false);
                qStartActivityForResult(MinePersonalSettingsEditPhoneNumActivity.class, num, change_phone);
                break;
            case R.id.password:
                break;
            case R.id.password_pay:
//                Intent in=new Intent(this, MineAddressActivity.class);
//                startActivity(in);
                if(isTeacher){
                    Bundle num2 = new Bundle();
                    num2.putBoolean("isTouxian", true);
                    qStartActivityForResult(EditPersonalInfoActivity.class, num2, 88);
                    break;
                }

                AddressPickTask task = new AddressPickTask(MyInfoActivity.this);
                task.setHideCounty(true);
                task.setCallback(new AddressPickTask.Callback() {
                    @Override
                    public void onAddressInitFailed() {
                        ToastUtil.show("数据初始化失败");
                    }

                    @Override
                    public void onAddressPicked(Province province, City city, County county) {
                        ToastUtil.show(province.getAreaName() + " " + city.getAreaName());
                        Log.d(TAG,province.getAreaName() + " " + city.getAreaName());
//                        passwordPay.setRightText(city.getAreaName());
                        gradeTx = city.getAreaName();

                        updataGradeInfo(gradeTx);
                    }
                });
                task.execute("a", "b");

                break;
            case R.id.quit_account:
                TipAlertDialog.showTip(mContext, null, null, "您确定退出登录吗？", new SuccessListener() {
                    @Override
                    public void success() {
                        Utils.logOut(mContext);
                    }
                });
                break;
        }
    }


    private void showPop() {

        new ActionSheetDialog(this)
                .builder()
                .setCancelable(false)
                .setCanceledOnTouchOutside(false)
                .addSheetItem("相机", ActionSheetDialog.SheetItemColor.Blue,
                        new ActionSheetDialog.OnSheetItemClickListener() {
                            @Override
                            public void onClick(int which) {
                                checkPic(true);
                            }
                        })
                .addSheetItem("图库", ActionSheetDialog.SheetItemColor.Blue,
                        new ActionSheetDialog.OnSheetItemClickListener() {
                            @Override
                            public void onClick(int which) {
                                checkPic(false);
                            }
                        }).show();
    }


    private void checkPic(boolean isCamera) {
        if(null == mPhotoSelectUtils){
            mPhotoSelectUtils = new PhotoSelectUtils(this);
            mPhotoSelectUtils.setTailor(1, 1, 350, 350);
        }

        if(isCamera){
            mPhotoSelectUtils.startTakeWayByCarema();
        }else {
            mPhotoSelectUtils.startTakeWayByAlbum();
        }

        mPhotoSelectUtils.setTakePictureCallBackListener(new PhotoSelectUtils.takePictureCallBackListener() {
            @Override
            public void successful(boolean isTailor, File outFile, Uri filePath) {
                Log.d(TAG,"filePath.getPath() = " + filePath.getPath());

                if(TextUtils.isEmpty(filePath.getPath())){
                    ToastUtil.show("图片选择失败，请重新选取");
                    return;
                }

                headImagePath = filePath.getPath();
                updataImageInfo(headImagePath);

//                Glide.with(MyInfoActivity.this).load(filePath)
//                        .placeholder(R.drawable.loading) //占位符 也就是加载中的图片，可放个gif
//                        .error(R.mipmap.morentouxiang60) //失败图片
//                        .bitmapTransform(new GlideCircleTransform(MyInfoActivity.this)).crossFade(1000).into(headImage);
            }

            @Override
            public void failed(int errorCode, List<String> deniedPermissions) {
                Log.d(TAG,"deniedPermissions = " + deniedPermissions);
            }

        });

    }


    //把本地的onActivityResult()方法回调绑定到对象
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(null != mPhotoSelectUtils) {
            mPhotoSelectUtils.attachToActivityForResult(requestCode, resultCode, data);
        }

        if(requestCode == 99){
            nickname.setRightText(SePref.getNickName());
        }

        if(requestCode == 88){
            passwordPay.setRightText(SePref.getIndividualitySign());
        }
    }

    //onRequestPermissionsResult()方法权限回调绑定到对象
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        mPhotoSelectUtils.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    //修改年级请求
    private void updataGradeInfo(final String gradeTx) {

//        //用户头像
//        if(TextUtils.isEmpty(headImagePath)){
//            ToastUtil.show("请选择用户头像");
//            return;
//        }
//
        if(isTeacher){
//            if(TextUtils.isEmpty(individualitySign.getText())){
//                ToastUtil.show("请填写教师头衔");
//                return;
//            }

        }else {
//            if(TextUtils.isEmpty(cityLocation)){
//                ToastUtil.show("请选择地区");
//                return;
//            }
//
            if(TextUtils.isEmpty(gradeTx)){
                ToastUtil.show("请选择年级");
                return;
            }
        }

        Map<String,RequestBody> params = new HashMap<>();
        params.put("sign", RequestBody.create(MediaType.parse("multipart/form-data"), "test"));
        params.put("uuid", RequestBody.create(MediaType.parse("multipart/form-data"), "5617222222"));
        params.put("version", RequestBody.create(MediaType.parse("multipart/form-data"), "1.0"));
        params.put("accessToken", RequestBody.create(MediaType.parse("multipart/form-data"), SePref.getToken()));

        StringBuilder pData = new StringBuilder();
        pData.append("id:" + SePref.getId());
        pData.append(",gender:" + 1);

        pData.append(",memberType:" + (isTeacher? 2:1));
        pData.append(",nickName:" + SePref.getNickName());

        if(isTeacher){
            pData.append(",individualitySign:" + SePref.getIndividualitySign());

        }else {
            pData.append(",grade:" + gradeTx);
            pData.append(",city:" + SePref.getCity());
        }

        params.put("requestData", RequestBody.create(MediaType.parse("multipart/form-data"), "{" + pData.toString() + "}"));

//        File file = new File(headImagePath);
//        RequestBody requestFile = RequestBody.create(MediaType.parse("multipart/form-data"), file);

//        MultipartBody.Part filePart = MultipartBody.Part.createFormData("files", file.getName(), requestFile);

        showLoading();
        // 执行请求
        Call<ResponseBody> call = createCallService(LoginService.class).updataMemberInfo(params,null);
        call.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call,
                                   Response<ResponseBody> response) {
                misLoading();
                try {
                    String data = response.body().string();
                    Log.d(TAG, "updataMemberInfo data = " + data);

                    JSONObject jsonObject = new JSONObject(data);

                    if(200 == jsonObject.getInt("code") &&
                            "true".equals(jsonObject.getString("responseData"))){

                        passwordPay.setRightText(gradeTx);
                        SePref.putGrade(gradeTx);
                        //nickname.setRightText(object.getString("nickName"));

//                        if(jsonObject.has("certPic")){
//                            SePref.setHeadImageUrl(jsonObject.getString("certPic"));
//                            headimg.setImageURI(jsonObject.getString("certPic"));
//                        }

                    }else {
                        if(jsonObject.has("error")){
                            ToastUtil.show("error:" + jsonObject.getString("error") );
                        }else {
                            ToastUtil.show("网络异常！" );
                        }
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                misLoading();
                Log.d("Upload error:", t.getMessage());
            }
        });

    }

    //修改头像请求
    private void updataImageInfo(final String headImagePath) {

        //用户头像
        if(TextUtils.isEmpty(headImagePath)){
            ToastUtil.show("请选择用户头像");
            return;
        }

        if(isTeacher){
//            if(TextUtils.isEmpty(individualitySign.getText())){
//                ToastUtil.show("请填写教师头衔");
//                return;
//            }

        }else {
//            if(TextUtils.isEmpty(cityLocation)){
//                ToastUtil.show("请选择地区");
//                return;
//            }
//
        }

        Map<String,RequestBody> params = new HashMap<>();
        params.put("sign", RequestBody.create(MediaType.parse("multipart/form-data"), "test"));
        params.put("uuid", RequestBody.create(MediaType.parse("multipart/form-data"), "5617222222"));
        params.put("version", RequestBody.create(MediaType.parse("multipart/form-data"), "1.0"));
        params.put("accessToken", RequestBody.create(MediaType.parse("multipart/form-data"), SePref.getToken()));

        StringBuilder pData = new StringBuilder();
        pData.append("id:" + SePref.getId());
        pData.append(",gender:" + 1);

        pData.append(",memberType:" + (isTeacher? 2:1));
        pData.append(",nickName:" + SePref.getNickName());

        if(isTeacher){
            pData.append(",individualitySign:" + SePref.getIndividualitySign());

        }else {
            pData.append(",grade:" + SePref.getGrade());
            pData.append(",city:" + SePref.getCity());
        }

        params.put("requestData", RequestBody.create(MediaType.parse("multipart/form-data"), "{" + pData.toString() + "}"));

        File file = new File(headImagePath);
        RequestBody requestFile = RequestBody.create(MediaType.parse("multipart/form-data"), file);

        MultipartBody.Part filePart = MultipartBody.Part.createFormData("files", file.getName(), requestFile);

        showLoading();
        // 执行请求
        Call<ResponseBody> call = createCallService(LoginService.class).updataMemberInfo(params,filePart);
        call.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call,
                                   Response<ResponseBody> response) {
                misLoading();
                try {
                    String data = response.body().string();
                    Log.d(TAG, "updataMemberInfo data = " + data);

                    JSONObject jsonObject = new JSONObject(data);

                    if(200 == jsonObject.getInt("code") &&
                            "true".equals(jsonObject.getString("responseData"))){

                        //headimg.setImageURI(Uri.parse(headImagePath));
                        Glide.with(MyInfoActivity.this).load(headImagePath)
                                .placeholder(R.drawable.loading) //占位符 也就是加载中的图片，可放个gif
                                .error(R.mipmap.morentouxiang60) //失败图片
                                .bitmapTransform(new GlideCircleTransform(MyInfoActivity.this)).crossFade(1000).into(headimg);
//                        passwordPay.setRightText(gradeTx);
//                        SePref.setHeadImageUrl(gradeTx);
                        //nickname.setRightText(object.getString("nickName"));

//                        if(jsonObject.has("certPic")){
//                            SePref.setHeadImageUrl(jsonObject.getString("certPic"));
//                            headimg.setImageURI(jsonObject.getString("certPic"));
//                        }

                    }else {
                        if(jsonObject.has("error")){
                            ToastUtil.show("error:" + jsonObject.getString("error") );
                        }else {
                            ToastUtil.show("网络异常！" );
                        }
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                misLoading();
                Log.d("Upload error:", t.getMessage());
            }
        });

    }


    @Override
    protected void onPause() {
        TipAlertDialog.dismiss();
        super.onPause();
    }
}

